package com.zoffy.bi.mq;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yupi.yucongming.dev.model.DevChatResponse;
import com.zoffy.bi.common.ErrorCode;
import com.zoffy.bi.exception.BusinessException;
import com.zoffy.bi.manager.AiManager;
import com.zoffy.bi.mapper.ChartMapper;
import com.zoffy.bi.model.entity.Chart;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class BiListener {
    @Resource
    private AiManager aiManager;
    @Resource
    private ChartMapper chartMapper;

    @RabbitListener(queues = "zoffyBi.bi")
    public void handleMessage(String chartId) {
        Chart chart = chartMapper.selectById(chartId);

        String chartType = chart.getChartType();
        String goal = chart.getGoal();
        String data = chart.getChartData();
        StringBuilder userInput = new StringBuilder();
        userInput.append("分析目标:").append("使用").append(chartType).append("类型的图表来").append(goal).append("\n");
        userInput.append("数据:").append("\n");

        userInput.append(data);
        String question = userInput.toString();


        //更新生成状态为生成中
        Chart updateChart = new Chart();
        updateChart.setId(chart.getId());
        //调用Ai
        com.yupi.yucongming.dev.common.BaseResponse<DevChatResponse> baseResponse = aiManager.doChat(question);
        System.out.println(baseResponse.getMessage());
        if (baseResponse.getMessage().equals("消息过长")) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "数据量过大");
        }
        String aiResponse = baseResponse.getData().getContent();
        //处理返回结果chart
        String[] splits = aiResponse.split("￥￥￥");
        String genChart = splits[1].trim();
        String genResult = splits[2].trim();
        //更新生成状态为成果并保存数据
        updateChart.setGenChart(genChart);
        updateChart.setGenResult(genResult);
        updateChart.setStatus("success");
        chartMapper.updateById(updateChart);
    }
}
